package org.ns.tomdog.utils;

import org.ns.tomdog.server.RequestParseException;
import org.ns.tomdog.server.ServerRequest;
import org.ns.tomdog.server.ServerResponse;
import org.ns.tomdog.server.support.ServerRequestImpl;
import org.ns.tomdog.servlet.Cookie;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class HttpParse {

    public static ServerRequest parse(InputStream inputStream) throws RequestParseException {
        return new ServerRequestImpl(inputStream);
    }
    public static Cookie[] parseCookie(String cookieContext) {
        String cookieArr[] = cookieContext.split(";");
        List<Cookie> cookies = new ArrayList<Cookie>();
        for (String cookieStr : cookieArr) {
            int keyIndex = cookieStr.indexOf("=");
            if (keyIndex != -1) {
                String key = cookieStr.substring(0, keyIndex);
                String val = cookieStr.substring(keyIndex + 1);
                Cookie cookie = new Cookie(key, val);
                cookies.add(cookie);
            }
        }
        return cookies.toArray(new Cookie[cookies.size()]);
    }

    public static boolean localFileOut(File file, ServerResponse response) {
        if (file.isDirectory() || !file.exists()) {
            return false;
        }
        try (FileInputStream fin = new FileInputStream(file);){
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fin.read(bytes)) != -1) {
                response.write(bytes, 0, len);
                response.flush();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    public static void main(String[] args) throws Exception{

        StringBuilder http = new StringBuilder();
        http.append("GET /123 http1.1\r\n")
                .append("key:val\r\n")
                .append("contentLength:4\r\n")
                .append("\r\n")
                .append("1234")
        ;
        ByteArrayInputStream inputStream = new ByteArrayInputStream(http.toString().getBytes(Charset.forName("UTF-8")));
        ServerRequest serverRequest = parse(inputStream);
        System.out.println(serverRequest.getHeaders());
        System.out.println(serverRequest.getMethod());
        System.out.println(serverRequest.getUrl());
        System.out.println(serverRequest.getVersion());

        InputStream in = serverRequest.getInputStream();
        byte[] bytes = new byte[4];
        System.out.println(in.read(bytes));
        System.out.println(Arrays.toString(bytes));
        System.out.println(new String(bytes, Charset.forName("UTF-8")));
        System.out.println(in.read());
    }
}
